﻿using Common;
using CommonTools;
using CommonTools.Controls;
using Flurl.Http;
using Microsoft.AspNetCore.SignalR.Client;
using OfficeOpenXml;
using shop.Bll;
using shop.cost;
using shop.job;
using shop.Model;
using shop.singlr;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace shop
{
    internal class myApp
    {
        /// <summary> 服务器地址 </summary>
        public static string Server
        {
            set => IniSet.WriteIniData("server", "address", value);
            get => IniSet.ReadIniData("server", "address", "");
        }



        #region 程序的全局变量: 硬件信息(IP,Mac)


        #region 硬件信息

        /// <summary> IP地址 </summary>
        public static string IpAddress
        {
            get
            {
                if (_ipAddress == "")
                {
                    KeyValuePair<string, string> ipmac = CommonTools.HardwareHelper.GetAddress();
                    _ipAddress = ipmac.Key;
                    _mac = ipmac.Value;
                }

                return _ipAddress;
            }
        }

        private static string _ipAddress = "";

        /// <summary> Mac地址 </summary>
        public static string Mac
        {
            get
            {
                if (_mac == "")
                {
                    KeyValuePair<string, string> ipmac = CommonTools.HardwareHelper.GetAddress();
                    _ipAddress = ipmac.Key;
                    _mac = ipmac.Value;
                }

                return _mac;
            }
        }

        private static string _mac = "";

        /// <summary> 计算机名称 </summary>
        public static string ComputerName
        {
            get { return CommonTools.HardwareHelper.GetComputerName(); }
        }

        #endregion


        #endregion

        #region 程序的全局变量: 公司名称, 主窗体, 最近文件, 版本号

        public static readonly SoftOwnerModel Owner = new SoftOwnerModel()
        {
            CompanyName = "企业管理系统",
            SoftwareName = "",
            Title = "企业管理系统",
            TitleOnLogin = "企业管理系统",
            Developer = "",
        };

        /// <summary>
        /// 所有程序都运行在这个dock父窗体中
        /// </summary>
        public static MainDockForm MainDock;


        /// <summary> 最近打开的文件 </summary>
        public static FileHistoryHelper RecentFiles;


        /// <summary> 版本号 </summary>
        public static Version MyVersion
        {
            get
            {
                if (_version == null)
                {
                    _version = new Version(FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion);
                }
                return _version;
            }
        }


        /// <summary> 下载文件路径 </summary>
        //public static string GetDownloadDir()
        //{
        //    var dir = IniSet.ReadIniData("app", "DownloadDir",string.Empty);
        //    if(string.IsNullOrEmpty(dir))
        //    {
        //        //打开选择对话框
        //        var dialog = new FolderBrowserDialog() { Description = "请选择文件下载的默认路径", };
        //        if(dialog.ShowDialog() == DialogResult.OK)
        //        {
        //            dir = dialog.SelectedPath;
        //            IniSet.WriteIniData("app", "DownloadDir", dir);
        //        }
        //        else
        //        {
                    //return null;
        //        }
        //    }

        //    if(!Directory.Exists(dir)) 
        //    {
        //        try
        //        {
        //            new DirectoryInfo(dir).Create();
        //        }
        //        catch (Exception)
        //        {
        //            MessageBox.Show("创建目录失败!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            return null;
        //        }
        //    }

        //    return dir;
        //}


        private static Version _version = null;

        #endregion


        ///// <summary> 报表 </summary>
        //public static BLL.Report.ReportService ReortService {private set; get; }

        /// <summary> 检查系统更新, 如果需要更新, 返回true </summary>
        public static bool AppUpdate(string con, bool onlyDownload = false)
        {

            //服务器地址改动后, 需要修改数据库的ftp地址
            var du = new DotUpdateApp.DotUpdateHelper()
                .UseSql(con)
                .SqlFile("ERPInstaller.exe")
                .QueryVersionCmd("SELECT AppName,Version, Remarks FROM dbo.JVersion where AppName='Gtong'")
                .RunExe("shop.exe");

            if (onlyDownload)
            {
                du.DownloadInstaller();
                return false;
            }
            else
            {
                if (du.Check())
                {
                    du.Start();
                    //du.StartTest();
                    return true;
                }
            }

            return false;
        }

        /// <summary> 检查服务器连接 </summary>
        public static bool TestServer(string ser, string catalog, string user, string pwd)
        {
            if (string.IsNullOrEmpty(ser))
            {
                return false;
            }

            string ip = "";
            if (ser.Contains(','))
                ip = ser.Substring(0, ser.IndexOf(','));
            else
                ip = ser;


            string con = $"server={ser};database={catalog};uid={user};pwd={pwd};timeout=20";  //超时1秒

            try
            {
                CommonTools.SqlHelper.ExecuteDataset(con, CommandType.Text, "select getdate()");
                return true;
            }
            catch (Exception)
            {
                //Console.WriteLine(e.Message);
                return false;
            }

        }


        /// <summary> 程序配置 </summary>
        public static void Init()
        {

            #region 系统功能配置 : 历史文件,语言, 打印


            ////最近的文件
            //RecentFiles= new FileHistoryHelper();

            //打印编辑器的配置
            //GtPrintEditor.TemplateConfig.Config = new BLL.PrintTemplateFuns();



            //基础资料配置
            CommonTools.CommonConfig.BllAssembly = Assembly.GetAssembly(typeof(shop.Bll.UserBll));
            CommonTools.CommonConfig.ModelAssembly = Assembly.GetAssembly(typeof(shop.Model.JSubMessage));
            CommonTools.CommonConfig.FormAssemblys = new[] { Assembly.GetAssembly(typeof(Program)) };

            //用户切换, 单据窗体
            shop.Bll.UserBll.UserChanged += () => DocDockxx.CurrentUser = shop.Bll.UserBll.CurrentUser;

            //基础资料


            //权限
            CommonConfig.CheckRight = shop.Bll.UserBll.CheckRight;
            CommonConfig.UserService = new shop.Bll.UserBll();
            CommonConfig.GetUser = () => shop.Bll.UserBll.CurrentUser;
            //CommonConfig.GetReportMenus = () => Program.ReortService.GetReportMenus(typeof(Program).Assembly);

            //Thread.Sleep(3000);

            //shop.Model.AutoMapStart.Start();

            //使用弹窗编辑基础资料
            CommonConfig.UseBasicEditDialog = true;

            #endregion


            OfficeOpenXml.ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;

            // 
            //ExcelPackage.License.SetNonCommercialPersonal("gutong"); //This will also set the Author property to the name provided in the argument.


            // 导出功能, 
            unvell.ReoGrid.Grid.SaveExcelAction = (g, f) => CommonTools.ReoGridHelper.Save(g, f, true);

        }



        public static IFlurlClient GetClient()
        {

            if (Model.DB.FSql.Ado.ConnectionString.Contains("192.168"))
            {
                return new FlurlClient("http://192.168.2.5:7652/api/");
            }
            else if (Model.DB.FSql.Ado.ConnectionString.Contains("frp"))
            {
                //#if DEBUG
                //                return new FlurlClient("http://frp.mazh.xyz:7652/api/");
                //                //return new FlurlClient("http://localhost:7652/api/");
                //#else
                return new FlurlClient("http://frp.mazh.xyz:7652/api/");
//#endif
            }
            else
            {
                return new FlurlClient("http://frp.mazh.xyz:7652/api/");
            }
        }



        #region signalr 客户端


        /// <summary>  </summary>
        private static BaseSignalRClient SignalRClient { get; set; }

        /// <summary>  </summary>
        public async static void StartJobMessage()
        {
            // 创建连接
            try
            {
                SignalRClient = await new BaseSignalRClient()
                .UseUrl("UserJobsHub?userId=" + UserBll.CurrentUser.DocID)
                //.UseDisplayStatus(str =>{ })
                .Start();

                // 处理消息
                SignalRClient.Connection.On<Result<int>>("JobDone", res =>
                {
                    Application.OpenForms[0]?.BeginInvoke(new Action(() =>  // 需要在主线程中调用
                    {
                        var form = Application.OpenForms[nameof(JobsForm)];
                        if (form != null)
                        {
                            (form as JobsForm)?.RefreshData(res.Data);
                        }

                        // 显式桌面弹窗提醒
                        new AlertForm()
                        .AlertMessage(res.Message )
                        .AlertClick(dialog =>
                        {
                            dialog.Close();
                            OpenJobsForm();
                        })
                        .AlertShowOk();
                    }));

                });
            }
            catch (Exception)
            {
                throw;
            }
        }


        #endregion



        //public static void OpenJobsForm(bool needRefresh, int jobId)
        public static void OpenJobsForm()
        {

            var form = Application.OpenForms[nameof(JobsForm)];
            if(form == null)
            {
                form = new JobsForm();
                form.Show();
            }
            else
            {
                form.BringToFront();
                //if(needRefresh)
                //{
                //    (form as JobsForm).RefreshData(jobId);
                //}
            }
        }


    }
}
